import {
    _decorator, CCString, error
} from 'cc';
import { VMBase } from './VMBase';
import { Filters } from '../filters';

const { ccclass, menu, property } = _decorator;

const LABEL_TYPE = {
    CC_LABEL: 'cc.Label',
    CC_RICH_TEXT: 'cc.RichText',
    CC_EDIT_BOX: 'cc.EditBox'
};

@ccclass("VMText")
@menu("StateSignals/VMText")
export class VMText extends VMBase {
    @property({
        tooltip: "开启模板模式，使用模板后支持多路径监听\n如: {{0}}:{{1}}"
        })
    useTemplate = false;

    @property({
        tooltip: "要监听的单个路径",
        visible: function() {
        return !this.useTemplate
        }
        })
    watchPath = '';

    @property({
        type: [CCString],
        tooltip: "要监听的多个路径",
        visible: function() {
        return this.useTemplate
        }
        })
    watchPathArr: string[] = [];

    @property({
        readonly: true
        })
    private labelType: string = LABEL_TYPE.CC_LABEL;

    private originText = '';

    private templateValueArr: (string | number)[] = [];

    onLoad(): void {
        super.onLoad();
        this.checkLabel();

        if (this.useTemplate) {
            this.originText = this.getLabelValue();
        }
    }

    onValueInit() {
        if (this.useTemplate) {
            const max = this.watchPathArr.length;
            for (let i = 0; i < max; i++) {
                this.templateValueArr[i] = this.getValue(this.watchPathArr[i], '');
            }
            this.setLabelValue(this.getReplaceText());
        } else {
            this.setLabelValue(this.getValue(this.watchPath, ''));
        }
    }

    onValueChanged(current: any, prev: any) {
        if (this.useTemplate) {
            this.templateValueArr = current;
            this.setLabelValue(this.getReplaceText());
        } else {
            this.setLabelValue(current);
        }
    }

    getReplaceText() {
        const templateText = this.originText;

        // 匹配所有的{{value}}
        const regexAll = /\{\{(.+?)\}\}/g;
        const regex = /\{\{(.+?)\}\}/;
        const res = templateText.match(regexAll);
        if (res == null) {
            return templateText;
        }
        let str = templateText;

        for (let i = 0; i < res.length; i++) {
            const e = res[i];
            const arr = e.match(regex);
            const indexNum = parseInt(arr![1] || '0', 10) || 0;
            const format = arr![1].split(':')[1] || '';

            let value = this.templateValueArr[indexNum];
            if (format) {
                value = Filters.format(format, value);
            }
            str = str.replace(e, String(value));
        }
        return str;
    }

    setLabelValue(value: string) {
        const component: any = this.getComponent(this.labelType);
        component.string = `${value}`;
    }

    getLabelValue(): string {
        const component: any = this.getComponent(this.labelType);
        return component.string;
    }

    private checkLabel() {
        const checkArray = [
            'cc.Label',
            'cc.RichText',
            'cc.EditBox',
        ];

        for (let i = 0; i < checkArray.length; i++) {
            const e = checkArray[i];
            const comp = this.node.getComponent(e);
            if (comp) {
                this.labelType = e;
                return true;
            }
        }

        error('没有挂载任何label组件');

        return false;
    }
}

export default VMText;
